home *** CD-ROM | disk | FTP | other *** search
/ MacGames Sampler / PHT MacGames Bundle.iso / MacSource Folder / Samples from the CD / C and C++ / Gnuplot 3.5 for Macintosh / SOURCES 3.5 / contour.c < prev    next >
Text File  |  1993-11-12  |  44KB  |  1,309 lines

  1. #ifndef lint
  2. static char *RCSid = "$Id: contour.c%v 3.50 1993/07/09 05:35:24 woo Exp $";
  3. #endif
  4.  
  5.  
  6. /* GNUPLOT - contour.c */
  7. /*
  8.  * Copyright (C) 1986 - 1993   Thomas Williams, Colin Kelley
  9.  *
  10.  * Permission to use, copy, and distribute this software and its
  11.  * documentation for any purpose with or without fee is hereby granted, 
  12.  * provided that the above copyright notice appear in all copies and 
  13.  * that both that copyright notice and this permission notice appear 
  14.  * in supporting documentation.
  15.  *
  16.  * Permission to modify the software is granted, but not the right to
  17.  * distribute the modified code.  Modifications are to be distributed 
  18.  * as patches to released version.
  19.  *  
  20.  * This software is provided "as is" without express or implied warranty.
  21.  * 
  22.  *
  23.  * AUTHORS
  24.  * 
  25.  *   Original Software:
  26.  *       Gershon Elber
  27.  * 
  28.  * There is a mailing list for gnuplot users. Note, however, that the
  29.  * newsgroup 
  30.  *    comp.graphics.gnuplot 
  31.  * is identical to the mailing list (they
  32.  * both carry the same set of messages). We prefer that you read the
  33.  * messages through that newsgroup, to subscribing to the mailing list.
  34.  * (If you can read that newsgroup, and are already on the mailing list,
  35.  * please send a message info-gnuplot-request@dartmouth.edu, asking to be
  36.  * removed from the mailing list.)
  37.  *
  38.  * The address for mailing to list members is
  39.  *       info-gnuplot@dartmouth.edu
  40.  * and for mailing administrative requests is 
  41.  *       info-gnuplot-request@dartmouth.edu
  42.  * The mailing list for bug reports is 
  43.  *       bug-gnuplot@dartmouth.edu
  44.  * The list of those interested in beta-test versions is
  45.  *       info-gnuplot-beta@dartmouth.edu
  46.  */
  47.  
  48. #include <stdio.h>
  49. #include "plot.h"
  50. #ifdef THINK_C
  51. #include "tout_protos.h"
  52. #endif
  53.  
  54. #define DEFAULT_NUM_OF_ZLEVELS  10  /* Some dflt values (setable via flags). */
  55. #define DEFAULT_NUM_APPROX_PTS  5
  56. #define DEFAULT_BSPLINE_ORDER  3
  57. #define MAX_NUM_OF_ZLEVELS      100 /* Some max. values (setable via flags). */
  58. #define MAX_NUM_APPROX_PTS      100
  59. #define MAX_BSPLINE_ORDER      10
  60.  
  61. #define INTERP_NOTHING   0            /* Kind of interpolations on contours. */
  62. #define INTERP_CUBIC     1                           /* Cubic spline interp. */
  63. #define APPROX_BSPLINE   2                         /* Bspline interpolation. */
  64.  
  65. #define LEVELS_AUTO            0        /* How contour levels are set */
  66. #define LEVELS_INCREMENTAL    1        /* user specified start & incremnet */
  67. #define LEVELS_DISCRETE        2        /* user specified discrete levels */
  68. #define ACTIVE   1                    /* Status of edges at certain Z level. */
  69. #define INACTIVE 2
  70.  
  71. #define OPEN_CONTOUR     1                                 /* Contour kinds. */
  72. #define CLOSED_CONTOUR   2
  73.  
  74. #define EPSILON  1e-5              /* Used to decide if two float are equal. */
  75. #define INFINITY 1e10
  76.  
  77. #ifndef TRUE
  78. #define TRUE     -1
  79. #define FALSE    0
  80. #endif
  81.  
  82. #define DEFAULT_NUM_CONTOURS    10
  83. #define MAX_POINTS_PER_CNTR     100
  84. #define SHIFT_Z_EPSILON        0.000301060 /* Dec. change of poly bndry hit.*/
  85.  
  86. #define abs(x)  ((x) > 0 ? (x) : (-(x)))
  87. #define sqr(x)  ((x) * (x))
  88.  
  89. #ifndef AMIGA_AC_5
  90. extern double sqrt();
  91. #endif /* not AMIGA_AC_5 */
  92. typedef double tri_diag[3];         /* Used to allocate the tri-diag matrix. */
  93. typedef double table_entry[4];           /* Cubic spline interpolation 4 coef. */
  94.  
  95. struct vrtx_struct {
  96.     double X, Y, Z;                       /* The coordinates of this vertex. */
  97.     struct vrtx_struct *next;                             /* To chain lists. */
  98. };
  99.  
  100. struct edge_struct {
  101.     struct poly_struct *poly[2];   /* Each edge belongs to up to 2 polygons. */
  102.     struct vrtx_struct *vertex[2]; /* The two extreme points of this vertex. */
  103.     struct edge_struct *next;                             /* To chain lists. */
  104.     int status, /* Status flag to mark edges in scanning at certain Z level. */
  105.     boundary;                   /* True if this edge is on the boundary. */
  106. };
  107.  
  108. struct poly_struct {
  109.     struct edge_struct *edge[3];           /* As we do triangolation here... */
  110.     struct poly_struct *next;                             /* To chain lists. */
  111. };
  112.  
  113. struct cntr_struct {           /* Contours are saved using this struct list. */
  114.     double X, Y;                          /* The coordinates of this vertex. */
  115.     struct cntr_struct *next;                             /* To chain lists. */
  116. };
  117.  
  118. static int test_boundary;    /* If TRUE look for contours on boundary first. */
  119. static struct gnuplot_contours *contour_list = NULL;
  120. static double crnt_cntr[MAX_POINTS_PER_CNTR * 2];
  121. static int crnt_cntr_pt_index = 0;
  122. static double contour_level = 0.0;
  123. static table_entry *hermit_table = NULL;    /* Hold hermite table constants. */
  124. static int num_of_z_levels = DEFAULT_NUM_OF_ZLEVELS;  /* # Z contour levels. */
  125. static int num_approx_pts = DEFAULT_NUM_APPROX_PTS;/* # pts per approx/inter.*/
  126. static int bspline_order = DEFAULT_BSPLINE_ORDER;   /* Bspline order to use. */
  127. static int interp_kind = INTERP_NOTHING;  /* Linear, Cubic interp., Bspline. */
  128. static int levels_kind = LEVELS_AUTO;  /* auto, incremental, discrete */
  129.  
  130.  
  131. static void gen_contours();
  132. static int update_all_edges();
  133. static struct cntr_struct *gen_one_contour();
  134. static struct cntr_struct *trace_contour();
  135. static struct cntr_struct *update_cntr_pt();
  136. static int fuzzy_equal();
  137. static void gen_triangle();
  138. static struct vrtx_struct *gen_vertices();
  139. static struct edge_struct *gen_edges_middle();
  140. static struct edge_struct *gen_edges();
  141. static struct poly_struct *gen_polys();
  142. static void free_contour();
  143. static void put_contour();
  144. static put_contour_nothing();
  145. static put_contour_cubic();
  146. static put_contour_bspline();
  147. static calc_tangent();
  148. static int count_contour();
  149. static complete_spline_interp();
  150. static calc_hermit_table();
  151. static hermit_interp();
  152. static prepare_spline_interp();
  153. static int solve_tri_diag();
  154. static gen_bspline_approx();
  155. static double fetch_knot();
  156. static eval_bspline();
  157.  
  158. /*
  159.  * Entry routine to this whole set of contouring module.
  160.  */
  161. struct gnuplot_contours *contour(num_isolines, iso_lines,
  162.                  ZLevels, approx_pts, int_kind, order1,
  163.                  levels_kind, levels_list)
  164. int num_isolines;
  165. struct iso_curve *iso_lines;
  166. int ZLevels, approx_pts, int_kind, order1;
  167. int levels_kind;
  168. double *levels_list;
  169. {
  170.     int i;
  171.     struct poly_struct *p_polys, *p_poly;
  172.     struct edge_struct *p_edges, *p_edge;
  173.     struct vrtx_struct *p_vrts, *p_vrtx;
  174.     double x_min, y_min, z_min, x_max, y_max, z_max, z, dz;
  175.      struct gnuplot_contours *save_contour_list;
  176.  
  177.     num_of_z_levels = ZLevels;
  178.     num_approx_pts = approx_pts;
  179.     bspline_order = order1 - 1;
  180.     interp_kind = int_kind;
  181.  
  182.     contour_list = NULL;
  183.  
  184.     if (interp_kind == INTERP_CUBIC) calc_hermit_table();
  185.  
  186.     gen_triangle(num_isolines, iso_lines, &p_polys, &p_edges, &p_vrts,
  187.         &x_min, &y_min, &z_min, &x_max, &y_max, &z_max);
  188.     crnt_cntr_pt_index = 0;
  189.  
  190.     dz = (z_max - z_min) / (num_of_z_levels + 1);
  191.     z = z_min;
  192.     for (i = 0; i < num_of_z_levels; i++) {
  193.         switch(levels_kind) {
  194.             case LEVELS_AUTO:
  195.                 /* Step from z_min+dz upto z_max-dz in num_of_z_levels times. */
  196.                 z += dz;
  197.                 break;
  198.             case LEVELS_INCREMENTAL:
  199.                 z = levels_list[0] + i * levels_list[1];
  200.                 break;
  201.             case LEVELS_DISCRETE:
  202.                 z = levels_list[i];
  203.                 break;
  204.         }
  205.         contour_level = z;
  206.          save_contour_list = contour_list;
  207.         gen_contours(p_edges, z + dz * SHIFT_Z_EPSILON, x_min, x_max,
  208.                                 y_min, y_max);
  209.          if(contour_list != save_contour_list) {
  210.              contour_list->isNewLevel = 1;
  211.              sprintf(contour_list->label, "%8.3g", z);
  212.          }
  213.     }
  214.  
  215.     /* Free all contouring related temporary data. */
  216.     while (p_polys) {
  217.     p_poly = p_polys -> next;
  218.     free (p_polys);
  219.     p_polys = p_poly;
  220.     }
  221.     while (p_edges) {
  222.     p_edge = p_edges -> next;
  223.     free (p_edges);
  224.     p_edges = p_edge;
  225.     }
  226.     while (p_vrts) {
  227.     p_vrtx = p_vrts -> next;
  228.     free (p_vrts);
  229.     p_vrts = p_vrtx;
  230.     }
  231.  
  232.     if (interp_kind == INTERP_CUBIC) free(hermit_table);
  233.  
  234.     return contour_list;
  235. }
  236.  
  237. /*
  238.  * Adds another point to the currently build contour.
  239.  */
  240. add_cntr_point(x, y)
  241. double x, y;
  242. {
  243.     int index;
  244.  
  245.     if (crnt_cntr_pt_index >= MAX_POINTS_PER_CNTR-1) {
  246.     index = crnt_cntr_pt_index - 1;
  247.     end_crnt_cntr();
  248.     crnt_cntr[0] = crnt_cntr[index * 2];
  249.     crnt_cntr[1] = crnt_cntr[index * 2 + 1];
  250.     crnt_cntr_pt_index = 1; /* Keep the last point as first of this one. */
  251.     }
  252.     crnt_cntr[crnt_cntr_pt_index * 2] = x;
  253.     crnt_cntr[crnt_cntr_pt_index * 2 + 1] = y;
  254.     crnt_cntr_pt_index++;
  255. }
  256.  
  257. /*
  258.  * Done with current contour - create gnuplot data structure for it.
  259.  */
  260. end_crnt_cntr()
  261. {
  262.     int i;
  263.     struct gnuplot_contours *cntr = (struct gnuplot_contours *)
  264.                     alloc((unsigned long)sizeof(struct gnuplot_contours),
  265.                           "gnuplot_contour");
  266.  
  267.     cntr->coords = (struct coordinate GPHUGE *) gpfaralloc((unsigned long)sizeof(struct coordinate) *
  268.                               ( unsigned long)crnt_cntr_pt_index,
  269.                            "contour coords");
  270.     for (i=0; i<crnt_cntr_pt_index; i++) {
  271.     cntr->coords[i].x = crnt_cntr[i * 2];
  272.     cntr->coords[i].y = crnt_cntr[i * 2 + 1];
  273.     cntr->coords[i].z = contour_level;
  274.     }
  275.     cntr->num_pts = crnt_cntr_pt_index;
  276.  
  277.     cntr->next = contour_list;
  278.     contour_list = cntr;
  279.      contour_list->isNewLevel = 0;
  280.  
  281.     crnt_cntr_pt_index = 0;
  282. }
  283.  
  284. /*
  285.  * Generates all contours by tracing the intersecting triangles.
  286.  */
  287. static void gen_contours(p_edges, z_level, x_min, x_max, y_min, y_max)
  288. struct edge_struct *p_edges;
  289. double z_level, x_min, x_max, y_min, y_max;
  290. {
  291.     int num_active,                        /* Number of edges marked ACTIVE. */
  292.     contour_kind;                /* One of OPEN_CONTOUR, CLOSED_CONTOUR. */
  293.     struct cntr_struct *p_cntr;
  294.  
  295.     num_active = update_all_edges(p_edges, z_level);           /* Do pass 1. */
  296.  
  297.     test_boundary = TRUE;        /* Start to look for contour on boundaries. */
  298.  
  299.     while (num_active > 0) {                                   /* Do Pass 2. */
  300.         /* Generate One contour (and update MumActive as needed): */
  301.     p_cntr = gen_one_contour(p_edges, z_level, &contour_kind, &num_active);
  302.     put_contour(p_cntr, z_level, x_min, x_max, y_min, y_max,
  303.                   contour_kind); /* Emit it in requested format. */
  304.     }
  305. }
  306.  
  307. /*
  308.  * Does pass 1, or marks the edges which are active (crosses this z_level)
  309.  * as ACTIVE, and the others as INACTIVE:
  310.  * Returns number of active edges (marked ACTIVE).
  311.  */
  312. static int update_all_edges(p_edges, z_level)
  313. struct edge_struct *p_edges;
  314. double z_level;
  315. {
  316.     int count = 0;
  317.  
  318.     while (p_edges) {
  319.     if (((p_edges -> vertex[0] -> Z >= z_level) &&
  320.          (p_edges -> vertex[1] -> Z <= z_level)) ||
  321.         ((p_edges -> vertex[1] -> Z >= z_level) &&
  322.          (p_edges -> vertex[0] -> Z <= z_level))) {
  323.         p_edges -> status = ACTIVE;
  324.         count++;
  325.     }
  326.     else p_edges -> status = INACTIVE;
  327.     p_edges = p_edges -> next;
  328.     }
  329.  
  330.     return count;
  331. }
  332.  
  333. /*
  334.  * Does pass 2, or find one complete contour out of the triangolation data base:
  335.  * Returns a pointer to the contour (as linked list), contour_kind is set to
  336.  * one of OPEN_CONTOUR, CLOSED_CONTOUR, and num_active is updated.
  337.  */
  338. static struct cntr_struct *gen_one_contour(p_edges, z_level, contour_kind,
  339.                                 num_active)
  340. struct edge_struct *p_edges;
  341. double z_level;
  342. int *contour_kind, *num_active;
  343. {
  344.     struct edge_struct *pe_temp;
  345.  
  346.     if (test_boundary) {    /* Look for something to start with on boundary: */
  347.     pe_temp = p_edges;
  348.     while (pe_temp) {
  349.         if ((pe_temp -> status == ACTIVE) && (pe_temp -> boundary)) break;
  350.         pe_temp = pe_temp -> next;
  351.     }
  352.     if (!pe_temp) test_boundary = FALSE;/* No more contours on boundary. */
  353.     else {
  354.         *contour_kind = OPEN_CONTOUR;
  355.         return trace_contour(pe_temp, z_level, num_active, *contour_kind);
  356.     }
  357.     }
  358.  
  359.     if (!test_boundary) {        /* Look for something to start with inside: */
  360.     pe_temp = p_edges;
  361.     while (pe_temp) {
  362.         if ((pe_temp -> status == ACTIVE) && (!(pe_temp -> boundary)))
  363.         break;
  364.         pe_temp = pe_temp -> next;
  365.     }
  366.     if (!pe_temp) {
  367.         *num_active = 0;
  368.         return NULL;
  369.     }
  370.     else {
  371.         *contour_kind = CLOSED_CONTOUR;
  372.         return trace_contour(pe_temp, z_level, num_active, *contour_kind);
  373.     }
  374.     }
  375.     return NULL;             /* We should never be here, but lint... */
  376. }
  377.  
  378. /*
  379.  * Search the data base along a contour starts at the edge pe_start until
  380.  * a boundary edge is detected or until we close the loop back to pe_start.
  381.  * Returns a linked list of all the points on the contour
  382.  * Also decreases num_active by the number of points on contour.
  383.  */
  384. static struct cntr_struct *trace_contour(pe_start, z_level, num_active,
  385.                                 contour_kind)
  386. struct edge_struct *pe_start;
  387. double z_level;
  388. int *num_active, contour_kind;
  389. {
  390.     int i, in_middle;       /* If TRUE the z_level is in the middle of edge. */
  391.     struct cntr_struct *p_cntr, *pc_tail;
  392.     struct edge_struct *p_edge = pe_start, *p_next_edge;
  393.     struct poly_struct *p_poly, *PLastpoly = NULL;
  394.  
  395.     /* Generate the header of the contour - the point on pe_start. */
  396.     if (contour_kind == OPEN_CONTOUR) pe_start -> status = INACTIVE;
  397.     (*num_active)--;
  398.     p_cntr = pc_tail = update_cntr_pt(pe_start, z_level, &in_middle);
  399.     if (!in_middle) {
  400.     return NULL;
  401.     }
  402.  
  403.     do {
  404.     /* Find polygon to continue (Not where we came from - PLastpoly): */
  405.     if (p_edge -> poly[0] == PLastpoly) p_poly = p_edge -> poly[1];
  406.     else p_poly = p_edge -> poly[0];
  407.     p_next_edge = NULL;          /* In case of error, remains NULL. */
  408.     for (i=0; i<3; i++)              /* Test the 3 edges of the polygon: */
  409.         if (p_poly -> edge[i] != p_edge)
  410.             if (p_poly -> edge[i] -> status == ACTIVE)
  411.             p_next_edge = p_poly -> edge[i];
  412.     if (!p_next_edge) {
  413.         pc_tail -> next = NULL;
  414.         free_contour(p_cntr);
  415.         return NULL;
  416.     }
  417.     p_edge = p_next_edge;
  418.     PLastpoly = p_poly;
  419.     p_edge -> status = INACTIVE;
  420.     (*num_active)--;
  421.     pc_tail -> next = update_cntr_pt(p_edge, z_level, &in_middle);
  422.     if (!in_middle) {
  423.         pc_tail -> next = NULL;
  424.         free_contour(p_cntr);
  425.         return NULL;
  426.     }
  427.         pc_tail = pc_tail -> next;
  428.     }
  429.     while ((pe_start != p_edge) && (!p_edge -> boundary));
  430.     pc_tail -> next = NULL;
  431.  
  432.     return p_cntr;
  433. }
  434.  
  435. /*
  436.  * Allocates one contour location and update it to to correct position
  437.  * according to z_level and edge p_edge. if z_level is found to be at
  438.  * one of the extreme points nothing is allocated (NULL is returned)
  439.  * and in_middle is set to FALSE.
  440.  */
  441. static struct cntr_struct *update_cntr_pt(p_edge, z_level, in_middle)
  442. struct edge_struct *p_edge;
  443. double z_level;
  444. int *in_middle;
  445. {
  446.     double t;
  447.     struct cntr_struct *p_cntr;
  448.  
  449.     t = (z_level - p_edge -> vertex[0] -> Z) /
  450.     (p_edge -> vertex[1] -> Z - p_edge -> vertex[0] -> Z);
  451.  
  452.     if (fuzzy_equal(t, 1.0) || fuzzy_equal(t, 0.0)) {
  453.         *in_middle = FALSE;
  454.         return NULL;
  455.     }
  456.     else {
  457.     *in_middle = TRUE;
  458.     p_cntr = (struct cntr_struct *) alloc((unsigned long)sizeof(struct cntr_struct),
  459.                             "contour cntr_struct");
  460.     p_cntr -> X = p_edge -> vertex[1] -> X * t +
  461.              p_edge -> vertex[0] -> X * (1-t);
  462.     p_cntr -> Y = p_edge -> vertex[1] -> Y * t +
  463.              p_edge -> vertex[0] -> Y * (1-t);
  464.     return p_cntr;
  465.     }
  466. }
  467.  
  468. /*
  469.  * Simple routine to decide if two real values are equal by simply
  470.  * calculating the relative/absolute error between them (< EPSILON).
  471.  */
  472. static int fuzzy_equal(x, y)
  473. double x, y;
  474. {
  475.     if (abs(x) > EPSILON)            /* Calculate relative error: */
  476.         return (abs((x - y) / x) < EPSILON);
  477.     else                    /* Calculate absolute error: */
  478.     return (abs(x - y) < EPSILON);
  479. }
  480.  
  481. /*
  482.  * Generate the triangles.
  483.  * Returns the lists (vrtxs edges & polys) via pointers to their heads.
  484.  */
  485. static void gen_triangle(num_isolines, iso_lines, p_polys, p_edges,
  486.     p_vrts, x_min, y_min, z_min, x_max, y_max, z_max)
  487. int num_isolines;
  488. struct iso_curve *iso_lines;
  489. struct poly_struct **p_polys;
  490. struct edge_struct **p_edges;
  491. struct vrtx_struct **p_vrts;
  492. double *x_min, *y_min, *z_min, *x_max, *y_max, *z_max;
  493. {
  494.     int i, grid_x_max = iso_lines->p_count;
  495.     struct vrtx_struct *p_vrtx1, *p_vrtx2, *pv_temp;
  496.     struct edge_struct *p_edge1, *p_edge2, *pe_tail1, *pe_tail2, *pe_temp,
  497.               *p_edge_middle, *pe_m_tail;
  498.     struct poly_struct *p_poly, *pp_tail;
  499.  
  500.     *p_polys = NULL;
  501.     *p_edges = NULL;
  502.     *p_vrts = NULL;
  503.     *z_min = INFINITY;
  504.     *y_min = INFINITY;
  505.     *x_min = INFINITY;
  506.     *z_max = -INFINITY;
  507.     *y_max = -INFINITY;
  508.     *x_max = -INFINITY;
  509.  
  510.     /* Read 1st row. */
  511.     p_vrtx1 = gen_vertices(grid_x_max, iso_lines->points,
  512.                x_min, y_min, z_min, x_max, y_max, z_max);
  513.     *p_vrts = p_vrtx1;
  514.     /* Gen. its edges.*/
  515.     pe_temp = p_edge1 = gen_edges(grid_x_max, p_vrtx1, &pe_tail1);
  516.     for (i = 1; i < grid_x_max; i++) {/* Mark one side of edges as boundary. */
  517.     pe_temp -> poly[1] = NULL;
  518.     pe_temp = pe_temp -> next;
  519.     }
  520.     for (i = 1; i < num_isolines; i++) { /* Read next column and gen. polys. */
  521.     iso_lines = iso_lines->next;
  522.         /* Get row into list. */
  523.         p_vrtx2 = gen_vertices(grid_x_max, iso_lines->points,
  524.                    x_min, y_min, z_min, x_max, y_max, z_max);
  525.         /* Generate its edges. */
  526.         p_edge2 = gen_edges(grid_x_max, p_vrtx2, &pe_tail2);
  527.     /* Generate edges from one vertex list to the other one: */
  528.     p_edge_middle = gen_edges_middle(grid_x_max, p_vrtx1, p_vrtx2,
  529.                                  &pe_m_tail);
  530.  
  531.     /* Now we can generate the polygons themselves (triangles). */
  532.     p_poly = gen_polys(grid_x_max, p_edge1, p_edge_middle, p_edge2,
  533.                                  &pp_tail);
  534.         pe_tail1 -> next = (*p_edges);      /* Chain new edges to main list. */
  535.         pe_m_tail -> next = p_edge1;
  536.     *p_edges = p_edge_middle;
  537.     pe_tail1 = pe_tail2;
  538.     p_edge1 = p_edge2;
  539.  
  540.     pv_temp = p_vrtx2;
  541.     while (pv_temp -> next) pv_temp = pv_temp -> next;
  542.     pv_temp -> next = *p_vrts;
  543.     *p_vrts = p_vrtx1 = p_vrtx2;
  544.  
  545.         pp_tail -> next = (*p_polys);       /* Chain new polys to main list. */
  546.     *p_polys = p_poly;
  547.     }
  548.  
  549.     pe_temp = p_edge1;
  550.     for (i = 1; i < grid_x_max; i++) {/* Mark one side of edges as boundary. */
  551.     pe_temp -> poly[0] = NULL;
  552.     pe_temp = pe_temp -> next;
  553.     }
  554.  
  555.     pe_tail1 -> next = (*p_edges);    /* Chain last edges list to main list. */
  556.     *p_edges = p_edge1;
  557.  
  558.     /* Update the boundary flag, saved in each edge, and update indexes: */
  559.     pe_temp = (*p_edges);
  560.     i = 1;
  561.  
  562.     while (pe_temp) {
  563.     pe_temp -> boundary = (!(pe_temp -> poly[0])) ||
  564.                   (!(pe_temp -> poly[1]));
  565.     pe_temp = pe_temp -> next;
  566.     }
  567. }
  568.  
  569. /*
  570.  * Handles grid_x_max 3D points (One row) and generate linked list for them.
  571.  */
  572. static struct vrtx_struct *gen_vertices(grid_x_max, points,
  573.                       x_min, y_min, z_min, x_max, y_max, z_max)
  574. int grid_x_max;
  575. struct coordinate GPHUGE *points;
  576. double *x_min, *y_min, *z_min, *x_max, *y_max, *z_max;
  577. {
  578.     int i;
  579.     struct vrtx_struct *p_vrtx, *pv_tail, *pv_temp;
  580.  
  581.     for (i=0; i<grid_x_max; i++) {/* Get a point and generate the structure. */
  582.         pv_temp = (struct vrtx_struct *) alloc((unsigned long)sizeof(struct vrtx_struct),
  583.                         "contour vertex");
  584.     pv_temp -> X = points[i].x;
  585.     pv_temp -> Y = points[i].y;
  586.     pv_temp -> Z = points[i].z;
  587.  
  588.     if (pv_temp -> X > *x_max) *x_max = pv_temp -> X; /* Update min/max. */
  589.     if (pv_temp -> Y > *y_max) *y_max = pv_temp -> Y;
  590.     if (pv_temp -> Z > *z_max) *z_max = pv_temp -> Z;
  591.     if (pv_temp -> X < *x_min) *x_min = pv_temp -> X;
  592.     if (pv_temp -> Y < *y_min) *y_min = pv_temp -> Y;
  593.     if (pv_temp -> Z < *z_min) *z_min = pv_temp -> Z;
  594.  
  595.     if (i == 0)                              /* First vertex in row: */
  596.         p_vrtx = pv_tail = pv_temp;
  597.     else {
  598.         pv_tail -> next = pv_temp;   /* Stick new record as last one. */
  599.         pv_tail = pv_tail -> next;    /* And continue to last record. */
  600.     }
  601.     }
  602.     pv_tail -> next = NULL;
  603.  
  604.     return p_vrtx;
  605. }
  606.  
  607. /*
  608.  * Combines N vertices in pair to form N-1 edges.
  609.  * Returns pointer to the edge list (pe_tail will point on last edge in list).
  610.  */
  611. static struct edge_struct *gen_edges(grid_x_max, p_vrtx, pe_tail)
  612. int grid_x_max;
  613. struct vrtx_struct *p_vrtx;
  614. struct edge_struct **pe_tail;
  615. {
  616.     int i;
  617.     struct edge_struct *p_edge, *pe_temp;
  618.  
  619.     for (i=0; i<grid_x_max-1; i++) {         /* Generate grid_x_max-1 edges: */
  620.     pe_temp = (struct edge_struct *) alloc((unsigned long)sizeof(struct edge_struct),
  621.                         "contour edge");
  622.     pe_temp -> vertex[0] = p_vrtx;              /* First vertex of edge. */
  623.     p_vrtx = p_vrtx -> next;                     /* Skip to next vertex. */
  624.     pe_temp -> vertex[1] = p_vrtx;             /* Second vertex of edge. */
  625.         if (i == 0)                                    /* First edge in row: */
  626.         p_edge = (*pe_tail) = pe_temp;
  627.     else {
  628.         (*pe_tail) -> next = pe_temp;   /* Stick new record as last one. */
  629.         *pe_tail = (*pe_tail) -> next;   /* And continue to last record. */
  630.      }
  631.     }
  632.     (*pe_tail) -> next = NULL;
  633.  
  634.     return p_edge;
  635. }
  636.  
  637. /*
  638.  * Combines 2 lists of N vertices each into edge list:
  639.  * The dots (.) are the vertices list, and the              .  .  .  .
  640.  *  edges generated are alternations of vertical edges      |\ |\ |\ |
  641.  *  (|) and diagonal ones (\).                              | \| \| \|
  642.  *  A pointer to edge list (alternate | , \) is returned    .  .  .  .
  643.  * Note this list will have (2*grid_x_max-1) edges (pe_tail points on last
  644.  * record).
  645.  */
  646. static struct edge_struct *gen_edges_middle(grid_x_max, p_vrtx1, p_vrtx2,
  647.                                 pe_tail)
  648. int grid_x_max;
  649. struct vrtx_struct *p_vrtx1, *p_vrtx2;
  650. struct edge_struct **pe_tail;
  651. {
  652.     int i;
  653.     struct edge_struct *p_edge, *pe_temp;
  654.  
  655.     /* Gen first (|). */
  656.     pe_temp = (struct edge_struct *) alloc((unsigned long)sizeof(struct edge_struct),
  657.                             "contour edge");
  658.     pe_temp -> vertex[0] = p_vrtx2;                 /* First vertex of edge. */
  659.     pe_temp -> vertex[1] = p_vrtx1;                /* Second vertex of edge. */
  660.     p_edge = (*pe_tail) = pe_temp;
  661.  
  662.     /* Advance in vrtx list grid_x_max-1 times, and gen. 2 edges /| for each.*/
  663.     for (i=0; i<grid_x_max-1; i++) {
  664.     /* The / edge. */
  665.     pe_temp = (struct edge_struct *) alloc((unsigned long)sizeof(struct edge_struct),
  666.                             "contour edge");
  667.     pe_temp -> vertex[0] = p_vrtx1;             /* First vertex of edge. */
  668.     pe_temp -> vertex[1] = p_vrtx2 -> next;    /* Second vertex of edge. */
  669.         (*pe_tail) -> next = pe_temp;       /* Stick new record as last one. */
  670.     *pe_tail = (*pe_tail) -> next;       /* And continue to last record. */
  671.  
  672.     /* The | edge. */
  673.     pe_temp = (struct edge_struct *) alloc((unsigned long)sizeof(struct edge_struct),
  674.                             "contour edge");
  675.     pe_temp -> vertex[0] = p_vrtx2 -> next;     /* First vertex of edge. */
  676.     pe_temp -> vertex[1] = p_vrtx1 -> next;    /* Second vertex of edge. */
  677.         (*pe_tail) -> next = pe_temp;       /* Stick new record as last one. */
  678.     *pe_tail = (*pe_tail) -> next;       /* And continue to last record. */
  679.  
  680.         p_vrtx1 = p_vrtx1 -> next;   /* Skip to next vertices in both lists. */
  681.         p_vrtx2 = p_vrtx2 -> next;
  682.     }
  683.     (*pe_tail) -> next = NULL;
  684.  
  685.     return p_edge;
  686. }
  687.  
  688. /*
  689.  * Combines 3 lists of edges into triangles:
  690.  * 1. p_edge1: Top horizontal edge list:        -----------------------
  691.  * 2. p_edge_middge: middle edge list:         |\  |\  |\  |\  |\  |\  |
  692.  *                                             |  \|  \|  \|  \|  \|  \|
  693.  * 3. p_edge2: Bottom horizontal edge list:     -----------------------
  694.  * Note that p_edge1/2 lists has grid_x_max-1 edges, while p_edge_middle has
  695.  * (2*grid_x_max-1) edges.
  696.  * The routine simple scans the two list    Upper 1         Lower
  697.  * and generate two triangle upper one        ----         | \
  698.  * and lower one from the lists:             0\   |2      0|   \1
  699.  * (Nums. are edges order in polys)             \ |         ----
  700.  * The routine returns a pointer to a                         2
  701.  * polygon list (pp_tail points on last polygon).          1
  702.  *                                                   -----------
  703.  * In addition, the edge lists are updated -        | \   0     |
  704.  * each edge has two pointers on the two            |   \       |
  705.  * (one active if boundary) polygons which         0|1   0\1   0|1
  706.  * uses it. These two pointer to polygons           |       \   |
  707.  * are named: poly[0], poly[1]. The diagram         |    1    \ |
  708.  * on the right show how they are used for the       -----------
  709.  * upper and lower polygons.                             0
  710.  */
  711. static struct poly_struct *gen_polys(grid_x_max, p_edge1, p_edge_middle,
  712.                             p_edge2, pp_tail)
  713. int grid_x_max;
  714. struct edge_struct *p_edge1, *p_edge_middle, *p_edge2;
  715. struct poly_struct **pp_tail;
  716. {
  717.     int i;
  718.     struct poly_struct *p_poly, *pp_temp;
  719.  
  720.     p_edge_middle -> poly[0] = NULL;                /* Its boundary! */
  721.  
  722.     /* Advance in vrtx list grid_x_max-1 times, and gen. 2 polys for each. */
  723.     for (i=0; i<grid_x_max-1; i++) {
  724.     /* The Upper. */
  725.     pp_temp = (struct poly_struct *) alloc((unsigned long)sizeof(struct poly_struct),
  726.                             "contour poly");
  727.     /* Now update polys about its edges, and edges about the polygon. */
  728.     pp_temp -> edge[0] = p_edge_middle -> next;
  729.     p_edge_middle -> next -> poly[1] = pp_temp;
  730.     pp_temp -> edge[1] = p_edge1;
  731.     p_edge1 -> poly[0] = pp_temp;
  732.     pp_temp -> edge[2] = p_edge_middle -> next -> next;
  733.     p_edge_middle -> next -> next -> poly[0] = pp_temp;
  734.     if (i == 0)                   /* Its first one in list: */
  735.         p_poly = (*pp_tail) = pp_temp;
  736.     else {
  737.         (*pp_tail) -> next = pp_temp;
  738.         *pp_tail = (*pp_tail) -> next;
  739.     }
  740.  
  741.     /* The Lower. */
  742.     pp_temp = (struct poly_struct *) alloc((unsigned long)sizeof(struct poly_struct),
  743.                             "contour poly");
  744.     /* Now update polys about its edges, and edges about the polygon. */
  745.     pp_temp -> edge[0] = p_edge_middle;
  746.     p_edge_middle -> poly[1] = pp_temp;
  747.     pp_temp -> edge[1] = p_edge_middle -> next;
  748.     p_edge_middle -> next -> poly[0] = pp_temp;
  749.     pp_temp -> edge[2] = p_edge2;
  750.     p_edge2 -> poly[1] = pp_temp;
  751.     (*pp_tail) -> next = pp_temp;
  752.     *pp_tail = (*pp_tail) -> next;
  753.  
  754.         p_edge1 = p_edge1 -> next;
  755.         p_edge2 = p_edge2 -> next;
  756.         p_edge_middle = p_edge_middle -> next -> next;
  757.     }
  758.     p_edge_middle -> poly[1] = NULL;                /* Its boundary! */
  759.     (*pp_tail) -> next = NULL;
  760.  
  761.     return p_poly;
  762. }
  763.  
  764. /*
  765.  * Calls the (hopefully) desired interpolation/approximation routine.
  766.  */
  767. static void put_contour(p_cntr, z_level, x_min, x_max, y_min, y_max, contr_kind)
  768. struct cntr_struct *p_cntr;
  769. double z_level, x_min, x_max, y_min, y_max;
  770. int contr_kind;
  771. {
  772.     if (!p_cntr) return;            /* Nothing to do if it is empty contour. */
  773.  
  774.     switch (interp_kind) {
  775.     case INTERP_NOTHING:              /* No interpolation/approximation. */
  776.         put_contour_nothing(p_cntr);
  777.         break;
  778.     case INTERP_CUBIC:                    /* Cubic spline interpolation. */
  779.         put_contour_cubic(p_cntr, z_level, x_min, x_max, y_min, y_max,
  780.                                 contr_kind);
  781.         break;
  782.     case APPROX_BSPLINE:                       /* Bspline approximation. */
  783.         put_contour_bspline(p_cntr, z_level, x_min, x_max, y_min, y_max,
  784.                                     contr_kind);
  785.         break;
  786.     }
  787.  
  788.     free_contour(p_cntr);
  789. }
  790.  
  791. /*
  792.  * Simply puts contour coordinates in order with no interpolation or
  793.  * approximation.
  794.  */
  795. static put_contour_nothing(p_cntr)
  796. struct cntr_struct *p_cntr;
  797. {
  798.     while (p_cntr) {
  799.     add_cntr_point(p_cntr -> X, p_cntr -> Y);
  800.     p_cntr = p_cntr -> next;
  801.     }
  802.     end_crnt_cntr();
  803. }
  804.  
  805. /*
  806.  * Find Complete Cubic Spline Interpolation.
  807.  */
  808. static put_contour_cubic(p_cntr, z_level, x_min, x_max, y_min, y_max,
  809.                                  contr_kind)
  810. struct cntr_struct *p_cntr;
  811. double z_level, x_min, x_max, y_min, y_max;
  812. int contr_kind;
  813. {
  814.     int num_pts, i;
  815.     double tx1, ty1, tx2, ty2;                    /* Tangents at end points. */
  816.     struct cntr_struct *pc_temp;
  817.  
  818.     num_pts = count_contour(p_cntr);         /* Number of points in contour. */
  819.  
  820.     if (num_pts > 2) {  /* Take into account 3 points in tangent estimation. */
  821.     calc_tangent(3, p_cntr -> X, p_cntr -> next -> X,
  822.             p_cntr -> next -> next -> X,
  823.             p_cntr -> Y, p_cntr -> next -> Y,
  824.             p_cntr -> next -> next -> Y, &tx1, &ty1);
  825.     pc_temp = p_cntr;
  826.     for (i=3; i<num_pts; i++) pc_temp = pc_temp -> next;/* Go to the end.*/
  827.     calc_tangent(3, pc_temp -> next -> next -> X,
  828.              pc_temp -> next -> X, pc_temp -> X,
  829.             pc_temp -> next -> next -> Y,
  830.             pc_temp -> next -> Y, pc_temp -> Y, &tx2, &ty2);
  831.         tx2 = (-tx2);   /* Inverse the vector as we need opposite direction. */
  832.         ty2 = (-ty2);
  833.     }
  834.     /* If following (num_pts > 1) is TRUE then exactly 2 points in contour.  */
  835.     else if (num_pts > 1) {/* Take into account 2 points in tangent estimat. */
  836.     calc_tangent(2, p_cntr -> X, p_cntr -> next -> X, 0.0,
  837.             p_cntr -> Y, p_cntr -> next -> Y, 0.0, &tx1, &ty1);
  838.     calc_tangent(2, p_cntr -> next -> X, p_cntr -> X, 0.0,
  839.             p_cntr -> next -> Y, p_cntr -> Y, 0.0, &tx2, &ty2);
  840.         tx2 = (-tx2);   /* Inverse the vector as we need opposite direction. */
  841.         ty2 = (-ty2);
  842.     }
  843.     else return(0);            /* Only one point (???) - ignore it. */
  844.  
  845.     switch (contr_kind) {
  846.     case OPEN_CONTOUR:
  847.         break;
  848.     case CLOSED_CONTOUR:
  849.         tx1 = tx2 = (tx1 + tx2) / 2.0;         /* Make tangents equal. */
  850.         ty1 = ty2 = (ty1 + ty2) / 2.0;
  851.         break;
  852.     }
  853.     complete_spline_interp(p_cntr, num_pts, 0.0, 1.0, tx1, ty1, tx2, ty2);
  854.     end_crnt_cntr();
  855. }
  856.  
  857. /*
  858.  * Find Bspline approximation for this data set.
  859.  * Uses global variable num_approx_pts to determine number of samples per
  860.  * interval, where the knot vector intervals are assumed to be uniform, and
  861.  * Global variable bspline_order for the order of Bspline to use.
  862.  */
  863. static put_contour_bspline(p_cntr, z_level, x_min, x_max, y_min, y_max,
  864.                                 contr_kind)
  865. struct cntr_struct *p_cntr;
  866. double z_level, x_min, x_max,  y_min, y_max;
  867. int contr_kind;
  868. {
  869.     int num_pts, order = bspline_order;
  870.  
  871.     num_pts = count_contour(p_cntr);         /* Number of points in contour. */
  872.     if (num_pts < 2) return(0);     /* Can't do nothing if empty or one points! */
  873.     /* Order must be less than number of points in curve - fix it if needed. */
  874.     if (order > num_pts - 1) order = num_pts - 1;
  875.  
  876.     gen_bspline_approx(p_cntr, num_pts, order, contr_kind);
  877.     end_crnt_cntr();
  878. }
  879.  
  880. /*
  881.  * Estimate the tangents according to the n last points where n might be
  882.  * 2 or 3 (if 2 onlt x1, x2).
  883.  */
  884. static calc_tangent(n, x1, x2, x3, y1, y2, y3, tx, ty)
  885. int n;
  886. double x1, x2, x3, y1, y2, y3, *tx, *ty;
  887. {
  888.     double v1[2], v2[2], v1_magnitude, v2_magnitude;
  889.  
  890.     switch (n) {
  891.     case 2:
  892.         *tx = (x2 - x1) * 0.3;
  893.         *ty = (y2 - y1) * 0.3;
  894.         break;
  895.     case 3:
  896.         v1[0] = x2 - x1;   v1[1] = y2 - y1;
  897.         v2[0] = x3 - x2;   v2[1] = y3 - y2;
  898.         v1_magnitude = sqrt(sqr(v1[0]) + sqr(v1[1]));
  899.         v2_magnitude = sqrt(sqr(v2[0]) + sqr(v2[1]));
  900.         *tx = (v1[0] / v1_magnitude) - (v2[0] / v2_magnitude) * 0.1;
  901.         *tx *= v1_magnitude * 0.1;  /* Make tangent less than magnitude. */
  902.         *ty = (v1[1] / v1_magnitude) - (v2[1] / v2_magnitude) * 0.1;
  903.         *ty *= v1_magnitude * 0.1;  /* Make tangent less than magnitude. */
  904.         break;
  905.     default:                       /* Should not happen! */
  906.         (*ty) = 0.1;
  907.         *tx = 0.1;
  908.         break;
  909.     }
  910. }
  911.  
  912. /*
  913.  * Free all elements in the contour list.
  914.  */
  915. static void free_contour(p_cntr)
  916. struct cntr_struct *p_cntr;
  917. {
  918.     struct cntr_struct *pc_temp;
  919.  
  920.     while (p_cntr) {
  921.     pc_temp = p_cntr;
  922.     p_cntr = p_cntr -> next;
  923.     free((char *) pc_temp);
  924.     }
  925. }
  926.  
  927. /*
  928.  * Counts number of points in contour.
  929.  */
  930. static int count_contour(p_cntr)
  931. struct cntr_struct *p_cntr;
  932. {
  933.     int count = 0;
  934.  
  935.     while (p_cntr) {
  936.     count++;
  937.     p_cntr = p_cntr -> next;
  938.     }
  939.     return count;
  940. }
  941.  
  942. /*
  943.  * Interpolate given point list (defined via p_cntr) using Complete
  944.  * Spline interpolation.
  945.  */
  946. static complete_spline_interp(p_cntr, n, t_min, t_max, tx1, ty1, tx2, ty2)
  947. struct cntr_struct *p_cntr;
  948. int n;
  949. double t_min, t_max, tx1, ty1, tx2, ty2;
  950. {
  951.     double dt, *tangents_x, *tangents_y;
  952.     int i;
  953.  
  954.     tangents_x = (double *) alloc((unsigned long) (sizeof(double) * n),
  955.                         "contour c_s_intr");
  956.     tangents_y = (double *) alloc((unsigned long) (sizeof(double) * n),
  957.                         "contour c_s_intr");
  958.  
  959.     if (n > 1) prepare_spline_interp(tangents_x, tangents_y, p_cntr, n,
  960.                     t_min, t_max, tx1, ty1, tx2, ty2);
  961.     else {
  962.     free((char *) tangents_x);
  963.     free((char *) tangents_y);
  964.     return(0);
  965.     }
  966.  
  967.     dt = (t_max-t_min)/(n-1);
  968.  
  969.     add_cntr_point(p_cntr -> X, p_cntr -> Y);           /* First point. */
  970.  
  971.     for (i=0; i<n-1; i++) {
  972.         hermit_interp(p_cntr -> X, p_cntr -> Y,
  973.                      tangents_x[i], tangents_y[i],
  974.              p_cntr -> next -> X, p_cntr -> next -> Y,
  975.                      tangents_x[i+1], tangents_y[i+1], dt);
  976.  
  977.         p_cntr = p_cntr -> next;
  978.     }
  979.  
  980.     free((char *) tangents_x);
  981.     free((char *) tangents_y);
  982. }
  983.  
  984. /*
  985.  * Routine to calculate intermidiate value of the Hermit Blending function:
  986.  * This routine should be called only ONCE at the beginning of the program.
  987.  */
  988. static calc_hermit_table()
  989. {
  990.     int i;
  991.     double t, dt;
  992.  
  993.     hermit_table = (table_entry *) alloc ((unsigned long) (sizeof(table_entry) *
  994.                         (num_approx_pts + 1)),
  995.                         "contour hermit table");
  996.     t = 0;
  997.     dt = 1.0/num_approx_pts;
  998.     for (i=0; i<=num_approx_pts; i++) {
  999.         hermit_table[i][0] = (t-1)*(t-1)*(2*t+1);             /* h00. */
  1000.         hermit_table[i][1] = t*t*(-2*t+3);                 /* h10. */
  1001.         hermit_table[i][2] = t*(t-1)*(t-1);                 /* h01. */
  1002.         hermit_table[i][3] = t*t*(t-1);                     /* h11. */
  1003.         t = t + dt;
  1004.     }
  1005. }
  1006.  
  1007. /*
  1008.  * Routine to generate an hermit interpolation between two points given as
  1009.  * two InterpStruct structures. Assume hermit_table is already calculated.
  1010.  * Currently the points generated are printed to stdout as two reals (X, Y).
  1011.  */
  1012. static hermit_interp(x1, y1, tx1, ty1, x2, y2, tx2, ty2, dt)
  1013. double x1, y1, tx1, ty1, x2, y2, tx2, ty2, dt;
  1014. {
  1015.     int i;
  1016.     double x, y, vec_size, tang_size;
  1017.  
  1018.     tx1 *= dt;  ty1 *= dt; /* Normalize the tangents according to param. t.  */
  1019.     tx2 *= dt;  ty2 *= dt;
  1020.  
  1021.     /* Normalize the tangents so that their magnitude will be 1/3 of the     */
  1022.     /* segment length. This tumb rule guaranteed no cusps or loops!          */
  1023.     /* Note that this normalization keeps continuity to be G1 (but not C1).  */
  1024.     vec_size = sqrt(sqr(x1 - x2) + sqr(y2 - y1));
  1025.     tang_size = sqrt(sqr(tx1) + sqr(ty1));                  /* Normalize T1. */
  1026.     if (tang_size * 3 > vec_size) {
  1027.     tx1 *= vec_size / (tang_size * 3);
  1028.     ty1 *= vec_size / (tang_size * 3);
  1029.     }
  1030.     tang_size = sqrt(sqr(tx2) + sqr(ty2));                  /* Normalize T2. */
  1031.     if (tang_size * 3 > vec_size) {
  1032.     tx2 *= vec_size / (tang_size * 3);
  1033.     ty2 *= vec_size / (tang_size * 3);
  1034.     }
  1035.  
  1036.     for (i=1; i<=num_approx_pts; i++) {      /* Note we start from 1 - first */
  1037.         x = hermit_table[i][0] * x1 +       /* point is not printed as it is */
  1038.             hermit_table[i][1] * x2 +   /* redundent (last on last section). */
  1039.             hermit_table[i][2] * tx1 +
  1040.             hermit_table[i][3] * tx2;
  1041.         y = hermit_table[i][0] * y1 +
  1042.             hermit_table[i][1] * y2 +
  1043.             hermit_table[i][2] * ty1 +
  1044.             hermit_table[i][3] * ty2;
  1045.     add_cntr_point(x, y);
  1046.     }
  1047. }
  1048.  
  1049. /*
  1050.  * Routine to Set up the 3*N mat for solve_tri_diag routine used in the
  1051.  * Complete Spline Interpolation. Returns TRUE of calc O.K.
  1052.  * Gets the points list in p_cntr (Of length n) and with tangent vectors tx1,
  1053.  * ty1 at starting point and tx2, ty2 and end point.
  1054.  */
  1055. static prepare_spline_interp(tangents_x, tangents_y, p_cntr, n, t_min, t_max,
  1056.                tx1, ty1, tx2, ty2)
  1057. double tangents_x[], tangents_y[];
  1058. struct cntr_struct *p_cntr;
  1059. int n;
  1060. double t_min, t_max, tx1, ty1, tx2, ty2;
  1061. {
  1062.     int i;
  1063.     double *r, t, dt;
  1064.     tri_diag *m;           /* The tri-diagonal matrix is saved here. */
  1065.     struct cntr_struct *p;
  1066. #ifdef THINK_C
  1067.     struct cntr_struct *dummy;
  1068.     struct cntr_struct *dummy2;
  1069.     double dummy3;
  1070. #endif
  1071.  
  1072.     m = (tri_diag *) alloc((unsigned long) (sizeof(tri_diag) * n),
  1073.                         "contour tri_diag");
  1074.     r = (double *) alloc((unsigned long) (sizeof(double) * n),
  1075.                         "contour tri_diag2");
  1076.     n--;
  1077.  
  1078.     p = p_cntr;
  1079.     m[0][0] = 0.0;    m[0][1] = 1.0;    m[0][2] = 0.0;
  1080.     m[n][0] = 0.0;    m[n][1] = 1.0;    m[n][2] = 0.0;
  1081.     r[0] = tx1;                           /* Set start tangent. */
  1082.     r[n] = tx2;                         /* Set end tangent. */
  1083.     t = t_min;
  1084.     dt = (t_max-t_min)/n;
  1085.     for (i=1; i<n; i++) {
  1086.        t = t + dt;
  1087.        m[i][0] = dt;
  1088.        m[i][2] = dt;
  1089.        m[i][1] = 2 * (m[i][0] + m[i][2]);
  1090. #ifdef THINK_C /* to allow code optimization P. Laval */
  1091.        dummy = p -> next;
  1092.        dummy2 = dummy -> next;
  1093.        r[i] = m[i][0] * ((dummy -> X) - (p -> X)) / m[i][2];
  1094.        dummy3 = (dummy2 -> X) - (dummy -> X);
  1095.        r[i] +=  m[i][2] * (dummy3) / m[i][0];
  1096. #else
  1097.        r[i] = m[i][0] * ((p -> next -> X) - (p -> X)) / m[i][2]
  1098.             + m[i][2] * ((p -> next -> next -> X) - 
  1099.                          (p -> next -> X)) / m[i][0];
  1100. #endif
  1101.        r[i] *= 3.0;
  1102.        p = p -> next;
  1103.     }
  1104.  
  1105.     if (!solve_tri_diag(m, r, tangents_x, n+1)) { /* Find the X(t) tangents. */
  1106.         free((char *) m);
  1107.         free((char *) r);
  1108.     int_error("Cannt interpolate X using complete splines", NO_CARET);
  1109.     }
  1110.  
  1111.     p = p_cntr;
  1112.     m[0][0] = 0.0;    m[0][1] = 1.0;    m[0][2] = 0.0;
  1113.     m[n][0] = 0.0;    m[n][1] = 1.0;    m[n][2] = 0.0;
  1114.     r[0] = ty1;                           /* Set start tangent. */
  1115.     r[n] = ty2;                         /* Set end tangent. */
  1116.     t = t_min;
  1117.     dt = (t_max-t_min)/n;
  1118.     for (i=1; i<n; i++) {
  1119.        t = t + dt;
  1120.        m[i][0] = dt;
  1121.        m[i][2] = dt;
  1122.        m[i][1] = 2 * (m[i][0] + m[i][2]);
  1123. #ifdef THINK_C /* to allow code optimization P. Laval */
  1124.        dummy = p -> next;
  1125.        dummy2 = dummy -> next;
  1126.        r[i] = m[i][0] * ((dummy -> Y) - (p -> Y)) / m[i][2];
  1127.        dummy3 = (dummy2 -> Y) - (dummy -> Y);
  1128.        r[i] += m[i][2] * (dummy3) / m[i][0];
  1129. #else
  1130.        r[i] = m[i][0] * ((p -> next -> Y) - (p -> Y)) / m[i][2]
  1131.             + m[i][2] * ((p -> next -> next -> Y) -
  1132.                          (p -> next -> Y)) / m[i][0];
  1133. #endif
  1134.        r[i] *= 3.0;
  1135.        p = p -> next;
  1136.     }
  1137.  
  1138.     if (!solve_tri_diag(m, r, tangents_y, n+1)) { /* Find the Y(t) tangents. */
  1139.         free((char *) m);
  1140.         free((char *) r);
  1141.     int_error("Cannt interpolate Y using complete splines", NO_CARET);
  1142.     }
  1143.     free((char *) m);
  1144.     free((char *) r);
  1145. }
  1146.  
  1147. /*
  1148.  * Solve tri diagonal linear system equation. The tri diagonal matrix is
  1149.  * defined via matrix M, right side is r, and solution X i.e. M * X = R.
  1150.  * Size of system given in n. Return TRUE if solution exist.
  1151.  */
  1152. static int solve_tri_diag(m, r, x, n)
  1153. tri_diag m[];
  1154. double r[], x[];
  1155. int n;
  1156. {
  1157.     int i;
  1158.     double t;
  1159.  
  1160.     for (i=1; i<n; i++) {   /* Eliminate element m[i][i-1] (lower diagonal). */
  1161.     if (m[i-1][1] == 0) return FALSE;
  1162.     t = m[i][0] / m[i-1][1];        /* Find ratio between the two lines. */
  1163.     m[i][0] = m[i][0] - m[i-1][1] * t;
  1164.     m[i][1] = m[i][1] - m[i-1][2] * t;
  1165.     r[i] = r[i] - r[i-1] * t;
  1166.     }
  1167.     /* Now do back subtitution - update the solution vector X: */
  1168.     if (m[n-1][1] == 0) return FALSE;
  1169.     x[n-1] = r[n-1] / m[n-1][1];               /* Find last element. */
  1170.     for (i=n-2; i>=0; i--) {
  1171.     if (m[i][1] == 0) return FALSE;
  1172.     x[i] = (r[i] - x[i+1] * m[i][2]) / m[i][1];
  1173.     }
  1174.     return TRUE;
  1175. }
  1176.  
  1177. /*
  1178.  * Generate a Bspline curve defined by all the points given in linked list p:
  1179.  * Algorithm: using deBoor algorithm
  1180.  * Note: if Curvekind is OPEN_CONTOUR than Open end knot vector is assumed,
  1181.  *       else (CLOSED_CONTOUR) Float end knot vector is assumed.
  1182.  * It is assumed that num_of_points is at list 2, and order of Bspline is less
  1183.  * than num_of_points!
  1184.  */
  1185. static gen_bspline_approx(p_cntr, num_of_points, order, contour_kind)
  1186. struct cntr_struct *p_cntr;
  1187. int num_of_points, order, contour_kind;
  1188. {
  1189.     int i, knot_index = 0, pts_count = 1;
  1190.     double dt, t, next_t, t_min, t_max, x, y;
  1191.     struct cntr_struct *pc_temp = p_cntr, *pc_tail;
  1192.  
  1193.     /* If the contour is Closed one we must update few things:               */
  1194.     /* 1. Make the list temporary circular, so we can close the contour.     */
  1195.     /* 2. Update num_of_points - increase it by "order-1" so contour will be */
  1196.     /*    closed. This will evaluate order more sections to close it!        */
  1197.     if (contour_kind == CLOSED_CONTOUR) {
  1198.     pc_tail = p_cntr;
  1199.     while (pc_tail -> next) pc_tail = pc_tail -> next;/* Find last point.*/
  1200.     pc_tail -> next = p_cntr;   /* Close contour list - make it circular.*/
  1201.     num_of_points += order;
  1202.     }
  1203.  
  1204.     /* Find first (t_min) and last (t_max) t value to eval: */
  1205.     t = t_min = fetch_knot(contour_kind, num_of_points, order, order);
  1206.     t_max = fetch_knot(contour_kind, num_of_points, order, num_of_points);
  1207.     next_t = t_min + 1.0;
  1208.     knot_index = order;
  1209.     dt = 1.0/num_approx_pts;            /* Number of points per one section. */
  1210.  
  1211.  
  1212.     while (t<t_max) {
  1213.     if (t > next_t) {
  1214.         pc_temp = pc_temp -> next;     /* Next order ctrl. pt. to blend. */
  1215.             knot_index++;
  1216.         next_t += 1.0;
  1217.     }
  1218.         eval_bspline(t, pc_temp, num_of_points, order, knot_index,
  1219.                         contour_kind, &x, &y);   /* Next pt. */
  1220.     add_cntr_point(x, y);
  1221.     pts_count++;
  1222.     /* As we might have some real number round off problems we must      */
  1223.     /* test if we dont produce too many points here...                   */
  1224.     if (pts_count + 1 == num_approx_pts * (num_of_points - order) + 1)
  1225.             break;
  1226.         t += dt;
  1227.     }
  1228.  
  1229.     eval_bspline(t_max - EPSILON, pc_temp, num_of_points, order, knot_index,
  1230.         contour_kind, &x, &y);
  1231.     /* If from round off errors we need more than one last point: */
  1232.     for (i=pts_count; i<num_approx_pts * (num_of_points - order) + 1; i++)
  1233.     add_cntr_point(x, y);                /* Complete the contour. */
  1234.  
  1235.     if (contour_kind == CLOSED_CONTOUR)     /* Update list - un-circular it. */
  1236.     pc_tail -> next = NULL;
  1237. }
  1238.  
  1239. /*
  1240.  * The recursive routine to evaluate the B-spline value at point t using
  1241.  * knot vector PKList, and the control points Pdtemp. Returns x, y after the
  1242.  * division by the weight w. Note that Pdtemp points on the first control
  1243.  * point to blend with. The B-spline is of order order.
  1244.  */
  1245. static eval_bspline(t, p_cntr, num_of_points, order, j, contour_kind, x, y)
  1246. double t;
  1247. struct cntr_struct *p_cntr;
  1248. int num_of_points, order, j, contour_kind;
  1249. double *x, *y;
  1250. {
  1251.     int i, p;
  1252.     double ti, tikp, *dx, *dy;      /* Copy p_cntr into it to make it faster. */
  1253.  
  1254.     dx = (double *) alloc((unsigned long) (sizeof(double) * (order + j)),
  1255.                         "contour b_spline");
  1256.     dy = (double *) alloc((unsigned long) (sizeof(double) * (order + j)),
  1257.                         "contour b_spline");
  1258.     /* Set the dx/dy - [0] iteration step, control points (p==0 iterat.): */
  1259.     for (i=j-order; i<=j; i++) {
  1260.         dx[i] = p_cntr -> X;
  1261.         dy[i] = p_cntr -> Y;
  1262.         p_cntr = p_cntr -> next;
  1263.     }
  1264.  
  1265.     for (p=1; p<=order; p++) {        /* Iteration (b-spline level) counter. */
  1266.     for (i=j; i>=j-order+p; i--) {           /* Control points indexing. */
  1267.             ti = fetch_knot(contour_kind, num_of_points, order, i);
  1268.             tikp = fetch_knot(contour_kind, num_of_points, order, i+order+1-p);
  1269.         if (ti == tikp) {   /* Should not be a problems but how knows... */
  1270.         }
  1271.         else {
  1272.         dx[i] = dx[i] * (t - ti)/(tikp-ti) +         /* Calculate x. */
  1273.             dx[i-1] * (tikp-t)/(tikp-ti);
  1274.         dy[i] = dy[i] * (t - ti)/(tikp-ti) +         /* Calculate y. */
  1275.             dy[i-1] * (tikp-t)/(tikp-ti);
  1276.         }
  1277.     }
  1278.     }
  1279.     *x = dx[j]; *y = dy[j];
  1280.     free((char *) dx);
  1281.     free((char *) dy);
  1282. }
  1283.  
  1284. /*
  1285.  * Routine to get the i knot from uniform knot vector. The knot vector
  1286.  * might be float (Knot(i) = i) or open (where the first and last "order"
  1287.  * knots are equal). contour_kind determines knot kind - OPEN_CONTOUR means
  1288.  * open knot vector, and CLOSED_CONTOUR selects float knot vector.
  1289.  * Note the knot vector is not exist and this routine simulates it existance
  1290.  * Also note the indexes for the knot vector starts from 0.
  1291.  */
  1292. static double fetch_knot(contour_kind, num_of_points, order, i)
  1293. int contour_kind, num_of_points, order, i;
  1294. {
  1295.     switch (contour_kind) {
  1296.     case OPEN_CONTOUR:
  1297.         if (i <= order) return 0.0;
  1298.         else if (i <= num_of_points) return (double) (i - order);
  1299.          else return (double) (num_of_points - order);
  1300.     case CLOSED_CONTOUR:
  1301.         return (double) i;
  1302.     default: /* Should never happen */
  1303.         return 1.0;
  1304.     }
  1305. #ifdef sequent
  1306.     return 1.0;
  1307. #endif
  1308. }
  1309.